<?php

/* Theme Functions  */
function excerpt($excerpt_length) {
  global $post;
	$content = $post->post_content;
	$words = explode(' ', $content, $excerpt_length + 1);
	if(count($words) > $excerpt_length) :
		array_pop($words);
		array_push($words, '...');
		$content = implode(' ', $words);
	endif;
  
  $content = strip_tags($content);
  
	echo $content;

}

function mytheme_comment($comment, $args, $depth) {
   $GLOBALS['comment'] = $comment; ?>
      <div class="comment-<?php comment_ID() ?>">
        <div class="comment-post">
          <div class="avatar"><?php echo get_avatar($comment,$size='40'); ?></div>
          <div class="comment-text">
          <h6><?php comment_author_link() ?></h6>
          <div class="comment-date"><?php comment_date('F jS, Y') ?> on <?php comment_time() ?></div>
          <?php if ($comment->comment_approved == '0') : ?>
    		  <p><?php echo __('Your comment is awaiting moderation.','vilisya');?></p>
    		<?php endif; ?>

          <?php comment_text() ?>
          <div class="clr"></div>
            <div class="reply">
               <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
            </div>  			
          </div>
        </div>
			</div>
<?php
}

function mytheme_ping($comment, $args, $depth) {
   $GLOBALS['comment'] = $comment; ?>
      <div class="commentlist" id="comment-<?php comment_ID() ?>">
			<div class="grid_1 listcomment alpha" >
        <?php echo get_avatar($comment,$size='60'); ?>
      </div>
		  <div class="placecomment grid_6">
				<h6><?php comment_author_link() ?>, <?php comment_date('F jS, Y') ?> on <?php comment_time() ?></h6>
  		<?php if ($comment->comment_approved == '0') : ?>
    		<p><?php echo __('Your comment is awaiting moderation.','vilisya');?></p>
    		<?php endif; ?>
    		<?php comment_text() ?>
    		<div class="clear"></div>
        <div class="reply">
           <?php comment_reply_link(array_merge( $args, array('depth' => $depth, 'max_depth' => $args['max_depth']))) ?>
        </div>  			
			</div>
			<div class="clear"></div>
		</div>
<?php
}

function centita_add_javascripts() {
  wp_enqueue_scripts('jquery');
  wp_enqueue_script( 's3Slider', get_template_directory_uri().'/js/s3Slider.js', array( 'jquery' ) );
	wp_enqueue_script( 'cycle', get_template_directory_uri().'/js/jquery.cycle.js', array( 'jquery' ) );
	wp_enqueue_script( 'jquery.nivo.slider.pack', get_template_directory_uri().'/js/jquery.nivo.slider.pack.js', array( 'jquery' ) );
	wp_enqueue_script( 'jqueryslidemenu', get_template_directory_uri().'/js/jqueryslidemenu.js', array( 'jquery' ) );  
  wp_enqueue_script( 'jquery.prettyPhoto', get_template_directory_uri().'/js/jquery.prettyPhoto.js', array( 'jquery' ) );
  wp_enqueue_script( 'jquery.tools.tabs.min', get_template_directory_uri().'/js/jquery.tools.tabs.min.js', array( 'jquery' ) );
  
  wp_register_script( 'jquery-gmap', get_template_directory_uri().'/js/jquery.gmap-1.1.0-min.js', array('jquery'));
  
  wp_enqueue_script('functions', get_template_directory_uri().'/js/functions.js', array('jquery'));
}

if (!is_admin()) {
  add_action( 'wp_print_scripts', 'centita_add_javascripts' ); 
}
if(get_option('centita_google_map_key')){
	function theme_add_gmap_script(){
		echo "\n<script type='text/javascript' src='http://maps.google.com/maps?file=api&amp;v=2&amp;key=".get_option('centita_google_map_key')."'></script>\n";
		wp_print_scripts( 'jquery-gmap');
	}
	add_filter('wp_head','theme_add_gmap_script');
}


function centita_add_stylesheet() { 
  $centita_style = get_option('centita_style');
  if ($centita_style== "") $centita_style = 'default.css';  
  ?>
	<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/prettyPhoto.css" type="text/css" media="screen" />
	<link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/jqueryslidemenu.css" type="text/css" media="screen" />
  <link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/nivo-slider.css" type="text/css" media="screen" />
  <link rel="stylesheet" href="<?php echo get_template_directory_uri(); ?>/css/custom_style.php" type="text/css" media="screen" />	
<?php 
}

add_action('wp_head', 'centita_add_stylesheet');


/* Register Nav Menu Features For Wordpress 3.0 */
register_nav_menus( array(
	'topnav' => __( 'Main Navigation')
) );

/* Remove Default Container for Nav Menu Features */
function centita_nav_menu_args( $args = '' ) {
	$args['container'] = false;
	return $args;
} 
add_filter( 'wp_nav_menu_args', 'centita_nav_menu_args' );

class description_walker extends Walker_Nav_Menu
{
    function start_el(&$output, $item, $depth, $args)
    {
         global $wp_query;
         $indent = ( $depth ) ? str_repeat( "\t", $depth ) : '';

         $class_names = $value = '';

         $classes = empty( $item->classes ) ? array() : (array) $item->classes;

         $class_names = join( ' ', apply_filters( 'nav_menu_css_class', array_filter( $classes ), $item ) );
         $class_names = ' class="'. esc_attr( $class_names ) . '"';

         $output .= $indent . '<li id="menu-item-'. $item->ID . '"' . $value . $class_names .'>';

         $attributes  = ! empty( $item->attr_title ) ? ' title="'  . esc_attr( $item->attr_title ) .'"' : '';
         $attributes .= ! empty( $item->target )     ? ' target="' . esc_attr( $item->target     ) .'"' : '';
         $attributes .= ! empty( $item->xfn )        ? ' rel="'    . esc_attr( $item->xfn        ) .'"' : '';
         $attributes .= ! empty( $item->url )        ? ' href="'   . esc_attr( $item->url        ) .'"' : '';

         $prepend = '';
         $append = '';
         $description  = ! empty( $item->description ) ? '<span class="descmenu">'.esc_attr( $item->description ).'</span>' : '';

         if($depth != 0)
         {
            $description = $append = $prepend = "";
         }

    		$item_output = $args->before;
    		$item_output .= '<a'. $attributes .'>';
    		$item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after;
    		$item_output .= '</a>';
    		$item_output .= $description.$args->link_after;
    		$item_output .= $args->after;

          $output .= apply_filters( 'walker_nav_menu_start_el', $item_output, $item, $depth, $args );
          }
}


function display_subtitle() {
  global $post;
  $menulist = wp_get_nav_menus();
  foreach ($menulist as $mlist) {
    $menu_id =  $mlist->term_id;
  }
  $menus = wp_get_nav_menu_items($menu_id);;
  if ($menus) {
    foreach ($menus as $menu) {
      if ($menu->object_id == $post->ID) {
        echo "<h1>$menu->description</h1>";
      }
    }  
  } else {
    $substitle = get_post_meta($post->ID,"subtitle",true);
    if ($substitle) echo "<h1>$substitle</h1>";  
  }  
}

function get_related_post() {
  global $post;  
  echo '<div id="recentPostList">';                                         
  $original_post = $post;
  $tags = wp_get_post_tags($post->ID);
  if ($tags) {
    $first_tag = $tags[0]->term_id;
    $args=array(
      'tag__in' => array($first_tag),
      'post__not_in' => array($post->ID),
      'showposts'=>2,
      'ignore_sticky_posts'=>1
     );     
    
    echo '<div id="related-post-title"><h4>'.__('Related Posts','centita').'</h4></div>';
    
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post(); 
      ?>
          <div class="related-item-wrapper"><!-- related item -->                           
          <h4><a href="<?php the_permalink();?>"><?php the_title();?></a></h4>
          <?php if (function_exists('has_post_thumbnail') && has_post_thumbnail()) {?>			
          <img src="<?php echo get_template_directory_uri();?>/timthumb.php?src=<?php echo thumb_url();?>&amp;h=110&amp;w=150&amp;zc=1" alt="" class="imgleft" />
          <?php } ?>
          <?php excerpt(15);?>
          <div class="clr"></div>
          </div>          
      <?php endwhile;
    }
  }
  echo '</div></div>';
  
  $post = $original_post;
  wp_reset_query();  
}

/* Posts List base on category*/
function centita_postslist($category, $num, $orderby="date") {  
  global $post;
  
  $category_id = get_cat_ID($category);
  
  $cat_num = ($num) ? $num : 4;
  $out = "";
  query_posts('cat='.$category_id.'&showposts='.$cat_num.'&orderby='.$orderby);
  
  while (have_posts()) : the_post();
  $out .= "<p>";
  if (function_exists('has_post_thumbnail') && has_post_thumbnail()) { 
    $out .= '<img src="'.get_template_directory_uri().'/timthumb.php?src='.thumb_url().'&amp;h=90&amp;w=90&amp;zc=1" alt="" class="imgleft" />';
  } 
  $out .= "<strong>".get_the_title()."</strong><br />";
  $out .= get_the_content();
  $out .= "</p>"; 
  endwhile; 
  wp_reset_query();
  
  return $out;
}

/* Services with child pages List */
function centita_pagelist($page_name, $num, $orderby="menu_order", $title="") {  
  global $post;
  
  $page_id = get_page_by_title($page_name);
  
  $services_num = ($num) ? $num : 6;
  $counter = 0;
  $out = "";
  
  query_posts('post_type=page&post_parent='.$page_id->ID.'&showposts='.$services_num.'&orderby='.$orderby);
    
  while (have_posts()) : the_post();
    $counter++;
    $out .= '<div class="box">';
    $out .= '<div class="box-main">';
    $out .= '<div class="icon">';
    if (function_exists('has_post_thumbnail') && has_post_thumbnail()) {
      $out .= '<img src="'.get_template_directory_uri().'/timthumb.php?src='.thumb_url().'&amp;h=64&amp;w=64&amp;zc=1" alt="" class="imgleft" />'."\n";
    }
    $out .= '</div>';
    $out .= '<p><strong><a href="'.get_permalink().'">'.get_the_title().'</a></strong><br />';
    $out .= get_the_excerpt().'</p>';
    $out .= '</div></div>';
    if ($counter %2 !=0) {
      $out .= '<div class="spacer">&nbsp;</div>'; 
    }
    endwhile;
  wp_reset_query();
  return $out;
}

function get_shortcode_name($name) {
  if (strstr(get_shortcode_regex(),$name)) {
    return false;
  }
}

function is_flash($file) {
  if (pathinfo($file, PATHINFO_EXTENSION) == "swf") {
    return true;
  } else {
    return false;
  }
}

function is_youtube($file) {
  if (preg_match('/youtube/i',$file)) {
    return true;
  } else {
    return false;
  }
}

function is_vimeo($file) {
  if (preg_match('/vimeo/i',$file)) {
    return true;
  } else {
    return false;
  }
}

/**
 * Disable Automatic Formatting on Posts
 * Thanks to TheBinaryPenguin (http://wordpress.org/support/topic/plugin-remove-wpautop-wptexturize-with-a-shortcode)
 */
function theme_formatter($content) {
	$new_content = '';
	$pattern_full = '{(\[raw\].*?\[/raw\])}is';
	$pattern_contents = '{\[raw\](.*?)\[/raw\]}is';
	$pieces = preg_split($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);
	
	foreach ($pieces as $piece) {
		if (preg_match($pattern_contents, $piece, $matches)) {
			$new_content .= $matches[1];
		} else {
			$new_content .= wptexturize(wpautop($piece));
		}
	}

	return $new_content;
}
remove_filter('the_content',	'wpautop');
remove_filter('the_content',	'wptexturize');

add_filter('the_content', 'theme_formatter', 99);

add_action( 'init', 'my_add_excerpts_to_pages' );
function my_add_excerpts_to_pages() {
     add_post_type_support( 'page', 'excerpt' );
}

add_filter( 'the_excerpt', 'shortcode_unautop');
add_filter( 'the_excerpt', 'do_shortcode');

add_filter( 'widget_text', 'shortcode_unautop');
add_filter( 'widget_text', 'do_shortcode');

// Make theme available for translation
// Translations can be filed in the /languages/ directory
load_theme_textdomain( 'centita', TEMPLATEPATH . '/languages' );

$locale = get_locale();
$locale_file = TEMPLATEPATH . "/languages/$locale.php";
if ( is_readable( $locale_file ) ) {
	require_once( $locale_file );
}

if (function_exists('add_theme_support')) {
	add_theme_support( 'post-thumbnails');
	set_post_thumbnail_size( 200, 200 );
	add_image_size('post_thumb', 616, 149, true);
}

function thumb_url(){  
  global $post;
  
  $thumb_src= wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), array( 2100,2100 ));
  return $thumb_src[0];
}

/* Thumbnail in Portfolio List */
if ( !function_exists('fb_AddThumbColumn') && function_exists('add_theme_support') ) {
 
function fb_AddThumbColumn($cols) {
 
$cols['thumbnail'] = __('Thumbnail','ebiz');
 
return $cols;
}
 
function fb_AddThumbValue($column_name, $post_id) {
   
  $width = (int) 100;
  $height = (int) 100;
   
  if ( 'thumbnail' == $column_name ) {
    // thumbnail of WP 2.9
    $thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
    // image from gallery
    $attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') );
    if ($thumbnail_id)
    $thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true );
    elseif ($attachments) {
      foreach ( $attachments as $attachment_id => $attachment ) {
        $thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
      }
    }
      if ( isset($thumb) && $thumb ) {
      echo $thumb;
      } else {
      echo __('None','ebiz');
      }
    }
  }
 
  // for posts
  add_filter( 'manage_posts_columns', 'fb_AddThumbColumn' );
  add_action( 'manage_posts_custom_column', 'fb_AddThumbValue', 10, 2 );
   
  // for Portfolio
  add_filter( 'manage_portfolio_columns', 'fb_AddThumbColumn' );
  add_action( 'manage_portfolio_custom_column', 'fb_AddThumbValue', 10, 2 );
}

add_filter('manage_edit-portfolio_columns', 'portfolio_columns');
function portfolio_columns($columns) {
    $columns['category'] = 'Portfolio Category';
    return $columns;
}

add_action('manage_posts_custom_column',  'portfolio_show_columns');
function portfolio_show_columns($name) {
    global $post;
    switch ($name) {
        case 'category':
            $cats = get_the_term_list( $post->ID, 'portfolio_category', '', ', ', '' );
            echo $cats;
    }
}

// Use shortcodes in text widget.
add_filter('widget_text', 'do_shortcode');

add_theme_support( 'automatic-feed-links' );

?>